<?php
namespace app\frontend\controllers;

use app\frontend\forms as Form;
use app\models\User;

class SiteController extends ControllerBase
{
    public function codeAction()
    {
        $session = $this->session;
        $session->start();
        $this->view->disable();
        $this->response->setHeader('Content-type','image/png');
        $str = "3,4,5,6,7,8,9,a,b,c,d,e,f,g";
        $list = explode(",",$str);
        $max = count($list) - 1;
        $verify = "";
        for($i = 0; $i <5;$i ++){
            $rand = mt_rand(0,$max);
            $verify .= $list[$rand];
        }
        $session->set('verifyCode',$verify);
        $im = imagecreate(58,28);
        $black = imagecolorallocate($im,0,0,0);
        $white = imagecolorallocate($im,255,255,255);
        imagefill($im,0,0,$white);
        imagestring($im,5,10,8,$verify,$black);
        imagepng($im);
        imagedestroy($im);
    }

    public function loginAction()
    {
        $this->tag->setTitle('综合办公信息管理系统');
        $form = new Form\LoginForm();
        $req = $this->request;
        if ($req->isPost()) {
            $param = $req->getPost();
            $sess = $this->session;
            $param['confirmVerifyCode'] = $sess->get('verifyCode');
            if($form->isValid($param)){
                $user = $form->getUser();
                $userSession = [
                    'username'=>$user->username,
                    'id'=>$user->id,
                ];

                $sess->set('user',$userSession);
                $sess->remove('verifyCode');

                $this->response->redirect('index/index');
                return;
            }
        }

        $this->view->form = $form;
    }

    public function registerAction()
    {
        $this->tag->setTitle('用户注册');
        $user = new User();
        $form = new Form\RegisterForm($user);
        $req = $this->request;
        if ($req->isPost()) {
            $param = $req->getPost();

            if($form->isValid($param)&&$user->save()){
                $this->response->redirect('site/login');
                return;
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $this->session->remove('username');
        $this->response->redirect('site/login');
        return;
    }
}